from find_delete_file import FindSuffixFile_DF
from tkinter import *
import logging, os, json
import log

#set file handler
path = os.getcwd() + '//' + 'config'
config_filename = path + '//'+ 'database.json'

class AppWin(object):
    def __init__(self, app_name='', app_size='200x200'):
        """
        Init the main window
        :param app_name: set the title of window
        :param app_size: set the size of window
        """
        #paras
        self.app_name = app_name
        self.app_size = app_size

        #init win & paras
        self.win = Tk()

        self.win.title(self.app_name)
        self.win.geometry(self.app_size)
        self.win.resizable(width=True, height=True)

        #logger
        self.logger = logging.getLogger("Master.UI")

        #data manage
        self.data_manage = ConfigManage(config_filename)

    def run(self):
        """
        Run loop
        :return:None
        """
        self.win.mainloop()

    @property
    def get_name(self):
        """
        Get name
        :return: app name
        """
        return  self.app_name

    def reset_name(self, app_name):
        """
        Reset name
        :return: None
        """
        self.app_name = app_name
        self.win.title(self.app_name)

    @property
    def get_size(self):
        """
        Get size
        :return: app size
        """
        return self.app_size

    def reset_size(self, app_size):
        """
        Reset size
        :return: None
        """
        self.app_size = app_size
        self.win.geometry(self.app_size)


class AppMainBasicFrame(AppWin):
    def __init__(self, app_name='', app_size='200x200', button_name=''):
        super().__init__(app_name, app_size)

        # path frame
        self.path_frm = Frame(self.win)
        self.path_frm.pack(side='top', fill='both', expand=True, padx=1, pady=1)

        # path label
        self.path_label = Label(self.path_frm, text="Path", width=5)
        self.path_label.pack(side='left', fill='both', expand=True, padx=1, pady=1)

        # path entry
        self.text_entry_var = StringVar()
        self.text_entry = Entry(self.path_frm, textvariable=self.text_entry_var)
        self.text_entry.pack(side='right', fill='both', expand=True, padx=1, pady=1)

        # suffix frame
        self.suffix_frm = Frame(self.win)
        self.suffix_frm.pack(side='top', fill='both', expand=True, padx=1, pady=1)

        # suffix label
        self.suffix_label = Label(self.suffix_frm, text="Suffix", width=5)
        self.suffix_label.pack(side='left', fill='both', expand=True, padx=1, pady=1)

        # suffix entry
        self.suffix_entry_var = StringVar()
        self.suffix_entry = Entry(self.suffix_frm, textvariable=self.suffix_entry_var)
        self.suffix_entry.pack(side='right', fill='both', expand=True, padx=1, pady=1)

        #create button
        self.button_name = button_name
        self.delete_btn = Button(self.win, text=self.button_name, relief='groove', command=self.delete_btn_response)
        self.delete_btn.pack(side='top', fill='both', expand=True, padx=1, pady=1)

        #set previous configuration
        self._set_default()

    def delete_btn_response(self):
        """
        Response to the delete button
        :return: None
        """
        #save data to local
        self._save_config()

        #get addr and suffix from window
        addr = self.text_entry_var.get()
        suffix = self.suffix_entry_var.get()

        #search and delete files
        fs = FindSuffixFile_DF(addr, suffix)
        fs.start_search()
        fs.start_delete()

        #print out search result
        self.logger.info(fs.get_search_result())

    def _set_default(self):
        """
        Set the path and suffix using previous data
        :return: None
        """
        # previous data
        data = self.data_manage.get_data()

        if data:
            # set path
            path = data['path']
            self.text_entry_var.set(path)

            # set suffix
            suffix = data['suffix']
            self.suffix_entry_var.set(suffix)

    def _save_config(self):
        """
        Save path and suffix to local
        :return: None
        """
        tmp_config = {}
        tmp_config['path'] = self.text_entry_var.get()
        tmp_config['suffix'] = self.suffix_entry_var.get()

        self.data_manage.save_data(tmp_config)

class ConfigManage(object):
    def __init__(self, filename):
        self.config_filename = filename
        self.logger = logging.getLogger('Master.Config')

    def save_data(self, data):
        """
        Save data to the file as json object
        :param data:
        :return: None
        """
        with open(self.config_filename, 'w') as f:
            json.dump(data, f)

    def get_data(self):
        """
        Get python data from the file
        :return: python data
        """
        with open(self.config_filename, 'r') as f:
            try:
                tmp_config = json.load(f)
                return tmp_config
            except:
                self.logger.warning("Need check if database.json file is empty.")
